<template>
  <div>
    <el-dialog class="add-prod" title="新增/修改装备" :visible.sync="dialogInfo_to" @close="close" @open="openDialog" width="650px" append-to-body>
        <el-form :rules="rules" :model="addprodForm" ref="addprodForm">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="装备编号" :label-width="formLabelWidth">
                <el-input v-model="addprodForm.prodCode" disabled placeholder="自动生成" style="width:80%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="prodName" label="装备名称" :label-width="formLabelWidth">
                <el-input v-model="addprodForm.prodName" style="width:80%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="规格" :label-width="formLabelWidth">
                <el-input v-model="addprodForm.prodSpecial" style="width:80%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商名称" :label-width="formLabelWidth">
                <el-select v-model="addprodForm.supplierId"  style="width:80%">
                  <el-option v-for="item in supplierlist" 
                    :key="item.supplierId" 
                    :label="item.supplierName" 
                    :value="item.supplierId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
               <el-form-item label="一级分类" :label-width="formLabelWidth">
                  <el-select v-model="addprodForm.categoryId"  style="width:80%" @change="selectFirstCate($event)">
                    <el-option v-for="item in prodCatelist" 
                      :key="item.categoryId" 
                      :label="item.categoryName" 
                      :value="item.categoryId">
                    </el-option>
                  </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="12">
               <el-form-item label="装备细类" :label-width="formLabelWidth">
                  <el-select v-model="addprodForm.categoryTwoId" placeholder="请先选择一级分类" style="width:80%">
                    <el-option v-for="item in twoCategory" 
                      :key="item.categoryTwoId" 
                      :label="item.categoryTwoName" 
                      :value="item.categoryTwoId">
                    </el-option>
                  </el-select>
                </el-form-item>
            </el-col>

            
          </el-row>

          <el-row :gutter="20">

            <el-col :span="12">
              <el-form-item label="单位" prop="emit" :label-width="formLabelWidth">
                <el-input v-model="addprodForm.emit" style="width:80%"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="产品图片" :label-width="formLabelWidth">
                <el-upload
                  action="#"
                  :file-list="fileList"
                  :auto-upload="true"
                  :show-file-list="false"
                  :http-request="uploadprodimg"
                  accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PNG,.GIF,.webp"
                  :on-success="handleAvatarSuccess">
                  <!-- <img v-if="imageUrl" :src="imageUrl" class="prev-img"> -->
                  <el-button size="small" type="primary">点击上传</el-button>
                  
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="close">取 消</el-button>
          <el-button size="small" type="primary" :loading="submitLoading" @click="submitProdinfo('addprodForm')">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { EditProduct, AddProduct, GetTwoCateById, uploadProdImg } from '@/api/prod';
import uploadimg from '@/components/uploadimg';
export default {
  name: 'addprod',
  props: ['dialogInfo', 'prodCatelist', 'choseProd', 'supplierlist'],
  components: {
    uploadimg
  },
  data() {
    return {
      fileList: [],
      imgloading: false,
      dialogInfo_to: false,
      submitLoading: false,
      addprodForm: {
        emit: "",
        categoryId: "",
        categoryTwoId: '',
        prodCode: "",
        prodImg: "",
        prodName: "",
        prodSpecial: "",
        supplierCode: "",
        supplierName: ""
      },
      twoCategory: [],
      formLabelWidth: '90px',
      rules: {
          prodName: [
            { required: true, message: '请输入装备名称', trigger: 'blur' },
          ],
          emit: [
            { required: true, message: '请输入单位', trigger: 'blur' },
          ],
      }
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      // this.advertForm.flash_screen = ''
    },
    uploadprodimg(param) {
      const loading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      var formdata = new FormData()
      var file = param.file;
      formdata.append('file', file)
      uploadProdImg(formdata).then(res => {
        if (res.data.code == 1 ) {
          setTimeout(() => {
            loading.close();
            this.$message({
              message: '上传成功',
              type: 'success'
            })
          }, 1000)
          this.addprodForm.prodImg = res.data.data
        }  
      })
      // this.getBase64(file).then(res => {
      //   let url = res.replace(/.*;base64,/, '')
      //   let reqdata = {
      //     file: url
      //   }
      //   uploadProdImg(reqdata).then(res => {
      //     console.log(res)
      //   })
      // });
    },
    // getBase64(file) {
    //   return new Promise(function(resolve, reject) {
    //     let reader = new FileReader();
    //     let imgResult = "";
    //     reader.readAsDataURL(file);
    //     reader.onload = function() {
    //       imgResult = reader.result;
    //     };
    //     reader.onerror = function(error) {
    //       reject(error);
    //     };
    //     reader.onloadend = function() {
    //       resolve(imgResult);
    //     };
    //   });
    // },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    close() {
      this.dialogInfo_to = false;
      this.resetForm();
      this.$emit("update:dialogInfo", false);
    },
    openDialog() {
        
    },
    selectFirstCate(value) {
      GetTwoCateById({categoryId:value}).then( res => {
        this.twoCategory = res.data;
      })
    },
    resetForm() {
      this.addprodForm.categoryId = '',
      this.addprodForm.categoryTwoId = '',
      this.addprodForm.prodCode = '',
      this.addprodForm.prodImg = '',
      this.addprodForm.prodName = "",
      this.addprodForm.prodSpecial = "",
      this.addprodForm.supplierCode = "",
      this.addprodForm.supplierName = ""
      this.addprodForm.emit = ""
    },
    submitProdinfo(formName) {
       this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.choseProd) {
                // 修改商品信息
                let reqData = {
                    emit: this.addprodForm.emit,
                    categoryId: this.addprodForm.categoryId,
                    categoryTwoId: this.addprodForm.categoryTwoId,
                    prodCode: this.addprodForm.prodCode,
                    prodId: this.choseProd.prodId,
                    prodImg: this.addprodForm.prodImg,
                    prodName: this.addprodForm.prodName,
                    prodSpecial: this.addprodForm.prodSpecial,
                    // "supplierCode": this.addprodForm.supplierCode,
                    supplierId: this.addprodForm.supplierId,
                }
                EditProduct(reqData).then(response => {
                    let data = response.data
                    this.$message({
                        message: data.msg,
                        type: 'success'
                    })
                    this.submitLoading = false;
                    this.$refs.addprodForm.resetFields();
                    this.dialogInfo_to = false;
                    this.resetForm();
                    this.$emit("update:dialogInfo", false);
                }).catch(error => {
                    this.submitLoading = false;
                })

              } else {
                // 新增商品信息
                let reqData = {
                    "emit": this.addprodForm.emit,
                    "categoryId": this.addprodForm.categoryId,
                     categoryTwoId: this.addprodForm.categoryTwoId,
                    "prodCode": this.addprodForm.prodCode,
                    "prodImg": this.addprodForm.prodImg,
                    "prodName": this.addprodForm.prodName,
                    "prodSpecial": this.addprodForm.prodSpecial,
                    // "supplierCode": this.addprodForm.supplierCode,
                    "supplierId": this.addprodForm.supplierId,
                }
                this.submitLoading = true;
                AddProduct(reqData).then(response => {
                    let data = response.data
                    this.$message({
                        message: data.msg,
                        type: 'success'
                    })
                    this.submitLoading = false;
                    this.$refs.addprodForm.resetFields();
                    this.dialogInfo_to = false;
                    this.resetForm();
                    this.$emit("update:dialogInfo", false);
                }).catch(error => {
                    this.submitLoading = false;
                })
              }
            } else {
              console.log('error submit!!');
              return false;
            }
        });
    }
  },
  watch: {
    dialogInfo(newVal,oldVal) {  
      this.dialogInfo_to = newVal;
    },
    choseProd(newVal) {
      if (newVal) {
        this.addprodForm = newVal;
        this.selectFirstCate(this.addprodForm.categoryId)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  
</style>